<?php
class ModelSaleTrimStock extends Model {
	public function getList($page = 1, $filter){
		$polist = M('trim')
		->join('(select user_id,fullname as user_name from user) u on u.user_id = trim.user_id','left')
		->join('(select count(1) as count, trim_id,packing_no from trim_product group by trim_id) ppc on ppc.trim_id = trim.id','left')
		->join('(select warehouse_id, name as warehouse_name from warehouse) w on w.warehouse_id = trim.warehouse_id','left')
		->order('trim.id DESC')
		->where($filter)->page($page)->limit($this->config->get('config_limit_admin'))->select();
		return $polist;
	}

	public function getTrimOperationBySku($filter){
		$map['trimp.sku'] = $filter['sku'];
		$map['_string'] = "trim.deliver_time>='".$filter['filter_date_start']."' AND trim.deliver_time<'".$filter['filter_date_end']."'";
		$map['trim.status'] = count(getTrimOrderStatus());
		$map['lg.logcenter_id'] = $filter['filter_logcenter'];
		$trim_operation = M('trim_product')
		->alias('trimp')
		->join('left join `trim` ON trim.id=trimp.trim_id')
		->join('left join `logcenters` lg ON trim.user_id=lg.user_id')
		->where($map)
		->field('qty,name,unit_price,option_name,packing_no,deliver_time')
		->order('option_name,deliver_time')
		->select();
		return $trim_operation;
	}

	public function getAllList($filter){
		$polist = M('trim')
		->join('(select vendors.user_id,  vendor_name from vendors) v on v.user_id = trim.vendor_id','left')
		->join('(select count(1) as count, trim_id from trim_product group by trim_id) ppc on ppc.trim_id = trim.id','left')
		->join('(select user_id, company as logcenter_company, address_1 as logcenter_address, logcenter_name from logcenters) lg on lg.user_id = trim.user_id','left')
		->order('trim.id DESC')
		->where($filter)->select();
		return $polist;
	}
	public function getAllProductList($filter){
		$trimlist = M('trim_product')
		->alias('tp')
		//->join('(select vendors.user_id,  vendor_name from vendors) v on v.user_id = ro.vendor_id','left')
		->join('left join `trim` ON trim.id=tp.trim_id')
		// ->join('(select user_id, company as logcenter_company, address_1 as logcenter_address, logcenter_name from logcenters) lg on lg.user_id = ro.user_id','left')
		->join('left join `logcenters` lg ON lg.user_id = trim.user_id')
		->join('left join `product` p ON p.product_id=tp.product_id')
		->join('left join `vendor` v ON v.vproduct_id=tp.product_id')
		->join('left join `vendors` vs ON vs.vendor_id=v.vendor')
		->field('tp.name,tp.sku,tp.option_name,tp.qty,trim.date_added,trim.deliver_time,p.model,trim.status,p.price as price,tp.unit_price,p.product_id,trim_id,vs.vendor_name,tp.packing_no,lg.logcenter_name')
		->order('trim.id DESC')
		->where($filter)
		->select();
		return $trimlist;
	}
	public function getListCount($filter){
		$count = M('trim')
		->join('vendors v on v.user_id = trim.vendor_id','left')
		->join(' `warehouse` w on w.warehouse_id = trim.warehouse_id','left')
		->where($filter)
		->count();
		return $count;
	}
	public function getProducts($fitler){
		$res = M('product')
			->join('product_description pd on pd.product_id = product.product_id')
			->join('vendor on vendor.vproduct_id = product.product_id')
			->field('product.*, pd.*, vendor.product_cost')
			->where($fitler)
			->where(array('pd.language_id'=>(int)$this->config->get('config_language_id')))
			->limit(5)->select();
		return $res;
	}
	public function getTrim($id){
		$trim = M('trim')->find($id);

		if($trim){
			$user = M('user')->find($trim['user_id']);
			$trim['creator'] = $user;
			$warehouse_info = M('warehouse')->where(array('warehouse_id'=>$trim['warehouse_id']))->find();
			$zone = M('zone')->where('zone_id='.$warehouse_info['zone_id'])->getField('name');
			$trim['warehouse_info'] = $warehouse_info;
		}
		return $trim;
	}
	public function getTrimProducts($id){
		$where['trim_id'] = $id;
		$products = M('trim_product')->where($where)->select();
		return $products;
	}
	public function getTrimHistory($id){
		$where['trim_id'] = $id;
		$history = M('trim_history')->where($where)->select();
		return $history;
	}
	public function getVendors($filter_name=''){
		return M('vendors')->limit(5)->where(array('vendor_name'=>array('like', "%$filter_name%")))->select();
	}
	public function addTrim($data, $user_id){
		$trim_data['user_id'] = $user_id;
		$trim_data['date_added'] = date('Y-m-d H:i:s', time());
		$trim_data['status'] = 1;
		$trim_data['warehouse_id'] = $data['warehouse_id'];
		$trim_data['included_order_ids'] = $data['included_order_ids'];
		$total = 0;
		foreach ($data['products'] as $key => $product) {
			$total += $product['qty']*$product['unit_price'];
		}
		$trim_data['total'] = $total;

		if(!$data['id']){
			$trim_id = M('trim')->add($trim_data);
		}
		foreach ($data['products'] as $key => $product) {
			$product_data['trim_id'] = $trim_id;
			$product_data['product_id'] = $product['product_id'];
			$product_data['qty'] = $product['qty'];
			$product_data['delivered_qty'] = $product['delivered_qty']?$product['delivered_qty']:0;
			$product_data['unit_price'] = $product['unit_price'];
			$product_data['price'] = $product_data['qty']* $product_data['unit_price'];
			$product_data['status'] = $product['status']?$product['status']:0;
			$product_data['name'] = $product['name'];
			$product_data['trim_status'] = $product['trim_status'];
			$product_data['product_code'] = $product['product_code'];
			$product_data['sku'] = $product['sku'];
			$product_data['comment'] = $product['comment'];
			$product_data['sort_order'] = 0;
			$product_data['option_id'] = $product['product_option_value_id'];
			$product_data['option_name'] = $product['name'];
			$product_data['packing_no'] = M('product')->where('product_id ='.$product['product_id'])->getField('packing_no');
			// var_dump($data['products']);

			M('trim_product')->add($product_data);

		}

		return $trim_id;
	}

	public function deleteTrim($id) {
		$where['trim_id'] = $id;
		$products = M('trim_product');
		$products->where($where)->delete();
		$trim = M('trim');
		$trim->where(array('id'=>$id))->delete();
	}

	public function setStock($trim_id, $to_save_stock) {
		//添加入库历史记录

		//修改ro单的delivered_qty
		$trim_product = M('trim_product');
		foreach ($to_save_stock as $trim_product_id => $qty) {
			$trim_product->where(array('id'=>$trim_product_id, 'trim_id'=>$trim_id))->setInc('qty', $qty);
			$trim_product_name = $trim_product->where(array('id'=>$trim_product_id, 'trim_id'=>$trim_id))->getField('name');
			$comment = "操作数量："."<br/>".$trim_product_name." ： 	".$qty;
			$this->addTrimHistory($trim_id, $this->user->getId(), $this->user->getUserName(), $comment);
		}
	}

	public function setComment($trim_id, $to_save_comment) {
		//添加入库历史记录

		//修改ro单的delivered_qty
		$trim_product = M('trim_product');
		foreach ($to_save_comment as $trim_product_id => $comment) {
			$data['comment'] = $comment;
			$trim_product
			->where(array('id'=>$trim_product_id, 'trim_id'=>$trim_id))
			->data($data)
			->save();

		}
	}

	public function changeTrimStatus($trim_id, $trim_status) {
		$ro = M('trim');
		$ro->data(array('id'=>$trim_id, 'status'=>$trim_status))->save();
	}

	public function findOrderWithoutVendor($orders) {
		$order_query = M('order_product op')
		->join('left join vendor v on v.vproduct_id=op.product_id')
		->where('op.order_id in (' . implode(',', $orders) . ') AND v.vendor is null')
		->field('v.vendor as vendor_id, op.name as name')
		->select();
		return $order_query;
	}

	public function getUserIdByVendorId($vendor_id) {
		$query = M('vendors')
		->where('vendor_id='.$vendor_id)
		->field('user_id')
		->find();
		if($query) {
			return $query['user_id'];
		} else {
			return 0;
		}
	}

	public function getVendorIdsFromOrders($orders) {
		$order_query = M('order_product op')
		->join('vendor v on v.vproduct_id=op.product_id')
		->where('op.order_id in (' . implode(',', $orders) . ')')
		->field('v.vendor as vendor_id')
		->group('v.vendor')
		->select();
		return $order_query;
	}

	public function getPoDataFromOrders($orders, $vendor_id=0) {
		$order_query = M('order_product op')
		->join('left join order_option oo on oo.order_product_id=op.order_product_id')
		->join('vendor v on v.vproduct_id=op.product_id')
		->where('op.order_id in (' . implode(',', $orders) . ') AND v.vendor="' . $vendor_id . '"')
		->group('op.product_id, oo.product_option_value_id')
		->field('v.vendor as vendor_id, op.product_id as product_id, v.product_cost as unit_price,
			v.product_cost*op.quantity as price, op.name as name, oo.product_option_value_id as option_id, oo.value as option_name, "" as sku, "" as comment, SUM(op.quantity) as qty, op.order_id')
		->select();
		return $order_query;
	}

	public function setPoGeneratedFlag($orders) {
		foreach ($orders as $order_id) {
			$Order = M('order');
			$Order->where(array('order_id'=>$order_id))->setInc('po_generated');
		}
	}

	public function getToBillPo($cur_month, $end_month, $billed_po_ids, $vendor_id = 0) {
		$complete_status = array('4','6'); // 4=>'已收货', 6=>'审核完成'
		$map['date_added'] = array('between',array($end_month, $cur_month));
		$map['status'] = array('in', $complete_status);
		if(!empty($billed_po_ids)) {
			$map['id'] = array('not in', $billed_po_ids);
		}
		$map['vendor_id'] = array('eq', $vendor_id);
		$query = M('po')->where($map)->select();
		return $query;
	}

	public function getVendorIdsFromPo($cur_month, $end_month, $billed_po_ids) {
    $complete_status = array('4','6'); // 4=>'已收货', 6=>'审核完成'
		$map['date_added'] = array('between',array($end_month, $cur_month));
		$map['status'] = array('in', $complete_status);
		if(!empty($billed_po_ids)) {
			$map['id'] = array('not in', $billed_po_ids);
		}
		$query = M('po')->where($map)->group('vendor_id')->field('vendor_id')->select();
		return $query;
  }

  public function addTrimHistory($trim_id, $user_id, $operator_name, $comment) {
  	$roHistory = M('trim_history');
  	$data = array('trim_id'=>$trim_id, 'user_id'=>$user_id,
  		'operator_name'=>$operator_name, 'comment'=>$comment,
  		'notify'=>0, 'date_added'=>date('Y-m-d H:i:s'));
  	$roHistory->data($data)->add();
  }

  public function setPoTotal($id, $new_total) {
  	$po = M('po');
		$po->where(array('id'=>$id, 'status'=>3))->data(array('total'=>$new_total))->save();
  }
  	public function addProductInitiai($trim_id){
  	$trim_product_model = M('trim_product');
  	$map['trim.id'] = $trim_id;
  	$trim_product_data = $trim_product_model
  	->alias('trimp')
  	->join('left join `trim` ON trim.id=trimp.trim_id')
  	->join('left join `logcenters` lg ON lg.user_id=trim.user_id')
  	->field('trimp.product_id,trimp.option_id,lg.logcenter_id,trimp.qty')
  	->where($map)
  	->select();

  	$product_initiai_model = M('product_initiai');
  	foreach ($trim_product_data as $key => $value) {
  		$initiai_map['option_id'] = $value['option_id']?$value['option_id']:-1;
  		$initiai_map['product_id'] = $value['product_id'];
  		$initiai_map['logcenter_id'] = $value['logcenter_id'];
  		$initiai_data = $product_initiai_model->where($initiai_map)->find();
  		if($initiai_data){
  			$edit_initiai_data['real_initiai'] = $value['qty'] + $initiai_data['real_initiai'];
  			$product_initiai_model->data($edit_initiai_data)->where($initiai_map)->save();
  		}else{
  			$edit_initiai_data['real_initiai'] = $value['qty'];
  			$edit_initiai_data['option_id'] = $value['option_id']?$value['option_id']:-1;
  			$edit_initiai_data['product_id'] = $value['product_id'];
  			$edit_initiai_data['logcenter_id'] = $value['logcenter_id'];
  			$edit_initiai_data['date_added'] = date('Y-m-d h:i:s',time());
  			$edit_initiai_data['initial_number'] = 0 ;
  			$product_initiai_model->data($edit_initiai_data)->add();
  		}
  	}
  }

    /* 仅用于导入损益单商品 */
    function searchProduct ($productCode){
        $sql = "
        SELECT
            POV.*,
            PD.`name`,
            P.`model`,P.`sku`,P.`packing_no`,P.`sale_price`,
            O.`type` AS `option_type`,
            OD.`name` AS `option_name`,
            OVD.`name` AS `option_value_name`,
            V.`product_cost`
        FROM
            `product_option_value` AS POV
            LEFT JOIN `product` AS P ON (P.`product_id`=POV.`product_id`)
            LEFT JOIN `product_description` AS PD ON (PD.`product_id`=POV.`product_id` AND PD.`language_id`=1)
            LEFT JOIN `option` AS O ON (O.`option_id`=POV.`option_id`)
            LEFT JOIN `option_description` AS OD ON (OD.`option_id`=POV.`option_id` AND OD.`language_id`=1)
            LEFT JOIN `option_value_description` AS OVD ON (OVD.`option_value_id`=POV.`option_value_id` AND OVD.`language_id`=1)
            LEFT JOIN `vendor` AS V ON (V.`vproduct_id`=POV.`product_id`)
        WHERE
            POV.`product_code`='".str_pad($productCode, 11, 0)."'";
        $query = $this->db->query($sql);
        $product = $query->row;
        $ret = array(
            'product_id' => $product['product_id'],
            'name' => $product['name'],
            'model' => $product['model'],
            'cost' => $product['product_cost'],//损益单不涉及到价格，不取数据
            'sku' => $product['sku'],
            // 'option_list' => array(
            //     'product_option_id' => $product['product_option_id'],
            //     'product_option_value' => array(
            //         array(
            //             'product_option_value_id' => $product['product_option_value_id'],
            //             'product_code' => $product['product_code'],
            //             'option_value_id' => $product['option_value_id'],
            //             'name' => $product['option_value_name'],
            //             'price' => $product['price'],
            //             'price_prefix' => $product['price_prefix'],
            //         ),
            //     ),
            //     'option_id' => $product['option_id'],
            //     'name' => $product['option_name'],
            //     'type' => $product['option_type'],
            //     'value' => '',
            //     'required' => 1,//product_option.required
            // ),
            /*
            'option' => array(
                array(
                    'product_option_id' => $product['product_option_id'],
                    'product_option_value' => array(
                        array(
                            'product_option_value_id' => $product['product_option_value_id'],
                            'product_code' => $product['product_code'],
                            'option_value_id' => $product['option_value_id'],
                            'name' => $product['option_value_name'],
                            'price' => $product['price'],
                            'price_prefix' => $product['price_prefix'],
                        ),
                    ),
                    'option_id' => $product['option_id'],
                    'name' => $product['option_name'],
                    'type' => $product['option_type'],
                    'value' => '',
                    'required' => 1,//product_option.required
                ),
            ),
            */
            'option_name' => $product['option_value_name'],
            'option_id' => $product['option_id'],
            'option' => $product['option_value_name'],
            'price' => $product['sale_price'],//损益单不涉及到价格，不取数据
            'packing_no' => $product['packing_no'],
            'product_code' => $product['product_code'],
            'clearance' => '0',
        );
        return $ret;
    }
}
